package com.zx.mes.hyl.security.core.validate.code.controller;

import com.zx.mes.hyl.security.core.properties.SecurityConstants;
import com.zx.mes.hyl.security.core.properties.SecurityProperties;
import com.zx.mes.hyl.security.core.validate.code.ValidateCodeGenerator;
import com.zx.mes.hyl.security.core.validate.code.ValidateCodeProcessorManager;
import com.zx.mes.hyl.security.core.validate.code.image.ImageCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.social.connect.web.HttpSessionSessionStrategy;
import org.springframework.social.connect.web.SessionStrategy;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.ServletWebRequest;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 生成校验码的请求处理器
 * @author huayunlong
 * @date 2018-5-31
 */
@RestController
public class ValidateCodeController {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private ValidateCodeProcessorManager validateCodeProcessorManager;

//    private SessionStrategy sessionStrategy = new HttpSessionSessionStrategy();

//    @Autowired
//    private ValidateCodeGenerator imageCodeGenerator;

//    @GetMapping(SecurityConstants.DEFAULT_VALIDATE_CODE_URL_PREFIX+"/image")
//    public void createCode(HttpServletRequest request,HttpServletResponse response) throws IOException {
//        ImageCode imageCode = (ImageCode) imageCodeGenerator.generate(new ServletWebRequest(request));
//
//        /* 将随机数存至 session 中 **/
//        sessionStrategy.setAttribute(new ServletWebRequest(request), SecurityConstants.DEFAULT_SESSION_IMAGE_KEY, imageCode);
//        /* 将生成的图片写到接口的响应中 **/
//        ImageIO.write(imageCode.getImage(), "JPEG", response.getOutputStream());
//    }

    @GetMapping(SecurityConstants.DEFAULT_VALIDATE_CODE_URL_PREFIX + "/{type}")
    public void createCode(HttpServletRequest request, HttpServletResponse response, @PathVariable String type){
        try {
            validateCodeProcessorManager.findValidateCodeProcessor(type).create(new ServletWebRequest(request,response));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
